package com.flymobi.mshop.util.service;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.flymobi.mshop.po.Users;
import com.flymobi.mshop.util.JsonHttpClient;

/**
 * @author gaoxf
 * 
 */
public class UsersService extends IService {
	public static class RegRst {
		public static final int SUCCESS = 1;
		public static final int ALREADY_EXISTS = 2;
	}

	public static class LoginRst {
		public static final int SUCCESS = 1;
		public static final int FAIL = 2;
	}

	public static Users login(String name, String pwd) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("act", Action.LOGIN);
		params.put("name", name);
		params.put("pwd", pwd);
		JSONArray ja = JsonHttpClient.post(serviceUrl, params);
		if(ja==null){
			return null;
		}
		int size = ja.length();
		String rst = "-1";
		for (int i = 0; i < size; i++) {
			JSONObject jo;
			try {
				jo = ja.getJSONObject(i);
				rst = jo.getString("rst");
				JSONObject usersJson=jo.getJSONObject("users");
				if("1".equals(rst)){
					Users u=new Users();
					u.setId(usersJson.getLong("id"));
					u.setMobile(usersJson.getString("mobile"));
					u.setJifen(usersJson.getLong("jifen"));
					u.setMoney(new Float(usersJson.getString("money")));
					System.out.println("service:Money="+u.getMoney());
					System.out.println("service:Mobile="+u.getMobile());
					System.out.println("service:Jifen="+u.getJifen());
					return u;
				}else{
					return null;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
//注册
	public static int reg(String name, String pwd) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("act", Action.REG);
		params.put("name", name);
		params.put("pwd", pwd);
		JSONArray ja = JsonHttpClient.post(serviceUrl, params);
		if(ja==null){
			return 0;
		}
		int size = ja.length();
		String rst = "-1";
		for (int i = 0; i < size; i++) {
			JSONObject jo;
			try {
				jo = ja.getJSONObject(i);
				rst = jo.getString("rst");
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return new Integer(rst);
	}
}
